import Assembler
import Constants
import instructionRun

RegisterSize = 33
MemorySize = 256

registers = []  # 为32个寄存器组，定义为全局变量
pc = 0

memory_cache = {}


# 输出语句染色方法，放置此处方便使用
class Bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'



def printSystemStatus(register_list):
    """
    打印当前系统状态
    :param register_list:
    :return:
    """
    print(f"{Bcolors.WARNING}$pc:{pc}{Bcolors.ENDC}")
    k = enumerate(register_list)
    for index, registerValue in enumerate(register_list):
        if isinstance(Constants.index2RegABIName[index], list):
            print(f"{Bcolors.WARNING}{Constants.index2RegName[index] + '/' + '/'.join(Constants.index2RegABIName[index]):8}:{registerValue}{Bcolors.ENDC}", end="\t")

        else:
            print(f"{Bcolors.WARNING}{Constants.index2RegName[index] + '/' + Constants.index2RegABIName[index]:8}:{registerValue}{Bcolors.ENDC}", end="\t")
        if (index + 1) % 8 == 0:
            print()
    print()
    for index in range(0, 8):
        print('{:032b}'.format(memory_cache[str(index)]), end='\t')
        if (index + 1) % 64 == 0:
            print()
    print()
    pass


def initialization():
    """
    初始化程序运行（系统运行）的初始状态，一般为PC、段寄存器等赋初值，此处简化操作，令PC=0，S=0，寄存器均为32位
    :return:
    """
    for i in range(0, RegisterSize):
        registers.append(0b00000000000000000000000000000000)
    for i in range(0, MemorySize):
        memory_cache[f"{i}"] = 1
    pass

def clear():
    """
    清空寄存器和存储
    :return:
    """
    for i in range(0, RegisterSize):
        registers[i] = 0
    for i in range(0, MemorySize):
        memory_cache[f"{i}"] = 1
    pass





if __name__ == '__main__':

    initialization()  # 初始化寄存器组

    command = ''

    for instruction in open("ProgramBinary.txt", "r"):
        instruction = instruction.strip()
        clear()
        func = instructionRun.switch[instruction[-2:]][instruction[:3]]
        instruction, registers, memory_cache, pc, command = func(instruction, registers, memory_cache, pc, command)
        print(command)
        printSystemStatus(registers)
